<?php

namespace Components;

use Kiri\Core\Json;
use Kiri\Router\Interface\ExceptionHandlerInterface;
use Psr\Http\Message\ResponseInterface;
use Throwable;

/**
 *
 */
class AppExceptionHandler implements ExceptionHandlerInterface
{


	/**
	 * @param Throwable $exception
	 * @param ResponseInterface $response
	 * @return ResponseInterface
	 * @throws \Exception
	 */
	public function emit(Throwable $exception, ResponseInterface $response): ResponseInterface
	{
		try {
			$response->getBody()->write($this->_format($exception));
			$response->withStatus($exception->getCode());
		} catch (Throwable $exception) {
			$response->getBody()->write($exception->getMessage());
			$response->withStatus(500);
		} finally {
			return $response->withHeader('Custom-Exception', get_called_class())
				->withHeader('Content-Type', 'text/html');
		}
	}


	/**
	 * @param Throwable $exception
	 * @return string|bool
	 */
	private function _format(Throwable $exception): string|bool
	{
		if ($exception->getCode() == 404) {
			return $exception->getMessage();
		}
		return Json::to(500, $exception->getMessage(), [
			'file' => $exception->getFile(),
			'line' => $exception->getLine(),
			'code' => $exception->getCode(),
		]);
	}


}
